$(function() {
	//初始化
	Begin();
	Date.prototype.Format = function (fmt) {
	    var o = {
	        "M+": this.getMonth() + 1,                 //月份
	        "d+": this.getDate(),                    //日
	        "h+": this.getHours(),                   //小时
	        "m+": this.getMinutes(),                 //分
	        "s+": this.getSeconds(),                 //秒
	        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
	        "S": this.getMilliseconds()             //毫秒
	    };
	    if (/(y+)/.test(fmt))
	        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	    for (var k in o)
	        if (new RegExp("(" + k + ")").test(fmt))
	            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	    return fmt;
	};
	
})

////////////--------------表格-数据--------------------////////////
var table = new VanyTable({
	el: "#table",
	url: "/msgStatistic/getMsDraftById",
	methodTypes:"GET",
	index: true, //选框
	selection: true, //编号
	pages: true, //是否需要分页，与scrollPage最好二选一
	pageSize: 10,
	pageIndex:1,
	scrollPage: false, 
	sels:[],//是否滚动分页，与pages最好二选一
	//height: 200,  //固定高度，滚动分页时需要使用
	// right、topRight、bottomLeft
	btnPostion: "bottomLeft",//底部菜单所在位置
	btnNotes: "", //按钮旁边是否需要文字
	btns: [{
		authority: "base_user_add",
		name: "批量删除",
		click: function() {
			 if (sels.length === 0) {
	                this.$alert('请选择要删除的信息。', '提示', {
	                    type: 'warning',
	                    customClass: "notLoadingThis"
	                });
	                return false;
	            }
	            var msgIds = sels.map(function (msg) {
	                return msg;
	            }).join(",");
	            console.log("msgIds:" + msgIds);
	            deleteMsg(msgIds);
	            //$('#batchDel').click();
	            
		}
	}],//底部菜单
	zidingyiBtn:'',  //底部菜单自定义
	zidingyiTop: '<el-form ref="form" :model="form" label-width="80px" class="btnright">' +
		'<el-row :gutter="20">' +
		'<el-col :span="18">' +
		'<el-form-item label="发送时间:"><el-date-picker id = "daterange" type="daterange" is-range v-model="form.Timevalue" placeholder="选择时间范围"></el-date-picker></el-form-item>' +
		'<el-form-item label="关键词:"><el-input @change="_restore" @keyup.enter.native="search" :on-icon-click="search" v-model="form.searchValue" placeholder="请输入您要搜索的内容" icon="search"></el-input></el-form-item>' +
		'<el-button id="search" @click="search()">搜索</el-button> <el-button style="display:none;" id="batchDel" @click="deleteMsg()"></el-button>' +
		'</el-col>' +
		'<el-col :span="6"  class="send"><el-button type="primary" onclick="sendMessage()">发消息</el-button></el-col>' +
		'</el-row>' +
		'</el-form>',  //头部按钮自定义，v-model中可以写form.value1到form.value8
	keys: [{
		"key": "msgtitle",
		"name": "标题消息"
	}, {
		"key": "process",
		"name": "发送进度",
		"template": "<div v-if=\"scope.row.sendResult === '0'\" style='color:#333;'>无</div>" +
			"<div v-else><el-progress :id='scope.row.msgId' class='updateProgressBar' :percentage='scope.row.progress'></el-progress></div>"
	}, {
		"key": "status",
		"name": "状态",
		"template": "<div v-if=\"scope.row.sendResult === '0'\"><span style='color:#333'>未发送</span> " +
//				"<el-tooltip placement='bottom'><div slot='content' v-text='scope.row.statusDetail'>" +
//				"</div><i class='el-icon-information'></i></el-tooltip>" +
				"</div>" +
				"<div v-else><span>正在发送</span></div>"
	},{
		"key": "createTime",	
		"name": "创建时间",
		"zidingyi": ":formatter='dateFormat'" //格式化Mon Sep 11 2017 18:36:20 GMT+0800 (中国标准时间)

	}, {
		"key": "operation",
		"name": "操作",
		"template": '<div v-if=\'scope.row.sendResult === "0"\'><span @click="handleEdit(scope.$index, scope.row)">编辑</span> | <span @click="handleDel(scope.$index, scope.row)">删除</span></div><div v-else style="color:#999"> — —</div>'
	}]//表格title
});

table.on("rowClick", function(index, row, event, column) {
	if(column.type === "selection" || column.property === "status") {
		return;
	}
	console.log("有一行被单击了");
});
table.on("selectionChange", function(selection) {
	var sels=[];
	$(selection).each(function(obj){
		sels.push(selection[obj].msgId);	
	})
	console.log("已选中"+sels+'共'+sels.length+"个")
});

table.getData({
	status: 0,
	/*pageIndex:1,
	pageSize:10,*/
	token:sessionStorage.token,
}, true);


table.on("handleEdit", function(index, row) {
	var self = this;
	this.$confirm("确认编辑\n" + row.msgtitle + "？")
		.then(function() {
			//done();
			document.cookie = "msgId="+row.msgId;
			document.cookie = "isEdit='true'";
            $("#content").load("templates/authority/sendMessage/sendMessage.html");
		});
	VanyAjax.prototype.hideLoading()
});

table.on("handleDel", function(index, row) {
	var self = this;
	this.$confirm("确认删除\n" + row.msgtitle + "？")
		.then(function() {
			deleteMsg(row.msgId)
		});
	VanyAjax.prototype.hideLoading()
});
/*table.on("deleteMsg", function() {
	debugger
	var self = this;
    this.$confirm('确认删除所选信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(function () {
        $.ajax({
    		url: "/sendedmsg/batchDeleteMsg",
    		method: "POST",
    		data:{msgIdList: msgIds},
    		success: function(newData) {
    			$('#search').click();
    		}
    	});        
    });
});*/
table.on("search", function(val) {
	//debugger
	//var now = new Date().Format("yyyy-MM-dd");
	var time = $('#daterange .el-input__inner').val();
	var startTime = '';
	var endTime = '';
	if(time!=""){
		startTime = time.substring(0,10)+' 00:00:00';
		endTime = time.substring(13,23)+' 23:59:59';
	}
	var keyWord = $($('.el-input__inner')[1]).val();
	table.getData({
		status: 0,
		/*pageIndex:1,
		pageSize:10,*/
		startTime:startTime,
		endTime:endTime,
		keyWord:keyWord,
		token:sessionStorage.token,
	}, true);
});

//初始化
function Begin() {
	//面包屑
	new Vue().$mount('#crumbs');
	sessionStorage.Jurisdiction = "base_tag_addBaseRootTag,base_team_delTeamUsesr,base_user_update,base_tag_modifyBaseTag,base_team_modify,base_role_modifyRFAAndRemove,base_tagUser_export,base_customerUser_export,base_role_modifyRoleInfo,base_customer_import,base_org_delete,base_customer_addTag,base_team_delete,base_org_export,base_role_modifyRoleUser,base_user_resetUserStatus,base_org_import,base_user_export,base_tag_modifyTag,base_customer_add,base_customer_modifyTag,base_user_resetUserPassword,base_user_import,base_team_addTeamUsers,base_tag_deleteTag,base_user_deleteUsers,base_org_update,base_role_deleteRoleUser,base_user_moveUsers,base_teamUser_export,base_tag_addBaseTag,base_team_add,base_tag_selectTagUser,base_tag_addTag,base_customer_delCustomer,base_customer_addRootTag,base_tag_addRootTag,base_org_add,base_user_updateOrderNum,base_tag_deleteTagUser,base_tag_deleteBaseTag,base_customer_deleteTag,base_org_updateOrderNum,base_user_add"
}

//特殊td
var hash = location.hash;
function OnlyTd() {
	console.log(1)
	if(hash != location.hash){
		 window.clearInterval(timerId);
		 return;
	}
	 var updateProgressBar = $(".updateProgressBar").map(function() {
	     return this.id;
	 }).get().join(',');
	$.ajax({
		url: "/msg/updateProgressBar?token="+sessionStorage.token+"&msgIds="+updateProgressBar,
		method: "GET",
		success: function(newData) {
			if(newData.resultData!=null){
				for(var i = 0; i < newData.resultData.length; i++) {
					$(".updateProgressBar").each(function(){
						if(this.id.indexOf(newData.resultData[i].msgId)!="-1"){
							$(this).find(".el-progress-bar__inner").css("width", newData.resultData[i].proportion);
							$(this).find(".el-progress__text").html(newData.resultData[i].proportion)
						}
					})
				}
			}
		}
	})
}

//进度条及时更新
var timerId=window.setInterval("OnlyTd()", 1000);


function sendMessage(){
	$("#content").load("templates/authority/sendMessage/sendMessage.html");
}
function deleteMsg(msgIds) {
    $.ajax({
		url: "/sendedmsg/batchDeleteMsg",
		method: "POST",
		data:{msgIdList: msgIds},
		success: function(newData) {
			$('#search').click();
		}      
    });
};
function FormatDate(d) {
    var date = new Date(d);
    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
}

